var gridStoreGroup = null;

Ext.define('component.marketing.rcPanel', {
	extend : 'Ext.form.Panel',
	initComponent:function(){
		
		var isPaydepositStoreList = [
			                         {"value":"0","text":"否"},
			                         {"value":"1","text":"是"}
			                         ];
		var isPaydepositStore = Ext.data.Store({
		    	autoDestroy: true,
		        fields :["value","text"],
		        data : isPaydepositStoreList
		});
		
		var agentGroupStore = new Ext.data.Store({
			fields: ["userName", "id"],
	        proxy:{
	            type:'ajax',
	            url:jypath+'/customer/customer/userByProjectIdForGroup',
	            reader:{
	                type: 'json', 
	                root: 'root'  // 数据
	           }
	        },
			autoLoad:true
	    });

		//新增
		var groupProjectBusiness = new Ext.data.Store({
			singleton:true,
			autoDestroy:true,
			fields: ["id", "projectName"],
			proxy:{
				type:'ajax',
				url:contextPath+'/estate/project/findProjectList?resourcesCode=menu_0003_0001',
				reader:{
					type: 'json',
					root: 'root'  //数据
				}
			} ,
			autoLoad: false
		});
		groupProjectBusiness.load({
			callback:function(records, options, success){
				var count = groupProjectBusiness.getCount();
				//debugger
				if(count>0){
					var id = groupProjectBusiness.getAt(0).get("id");
					Ext.getCmp('groupProjectStore').setValue(id)
				}
				if(Ext.Array.contains(idata,"marketing:list:all")){
					var data = {"projectName": "全部", "id": '-1'};
					var rs = Ext.create(data);
					groupProjectBusiness.insert(count+1, rs);
				}
			}
		});

		var form = Ext.create("Ext.form.Panel", {
			minHeight:170,
		    title: "查询条件",
		    collapsible: true,  //可折叠
		    autoScroll: false,   //自动创建滚动条
		    defaultType: 'textfield',
		    defaults: {
		    	 anchor: '100%'
		    },
		    fieldDefaults: {
		        margin: 2,
		        labelWidth: 80,
	            labelAlign: "right",
	            margin: "5 0 0 0"
		    },
		    items: [
		    	{
		            xtype: "container",
		            layout: "hbox",
		            items: [
		            	//新增
						{
							id:'groupProjectStore',
							store:groupProjectBusiness,
							xtype:'combobox',
							name: "projectId",
							valueField: "id",
							displayField: "projectName",
							fieldLabel:'所属项目',
							queryMode:'local',
							typeAhead: true,
							editable: false
						},
		            		//权限资源隐藏字段
							{xtype:"textfield", name:"resourcesCode", value: resourcesCode, hidden: true},
							{xtype:"textfield", name:"resourcesName", value: "resName_pin_list", hidden: true},
		                    { 
					            xtype:'combobox',  
					            id:'isPaydeposit',  
					            store: isPaydepositStore,
					            displayField: "text",           
					            valueField: "value",  
					            fieldLabel:'是否无房认筹',  
					            typeAhead: true,
				    			name:'isPaydeposit'
			            	},
	                    	{ xtype: "textfield", name:"roomName", fieldLabel: "房号",
		                    	listeners:{
		                    		focus:function(){
		                    			var selectWindow=Ext.create('component.estate.selectWindow',{
				           		 	        callbackFun: function (record) {
				           		 	          var result=Ext.JSON.decode(record);
				           		 	          if(result){
				           		 	        	  form.getForm().findField("roomName").setValue(result.roomName);
				           		 	        	  gridStoreGroup.getProxy().extraParams.roomId=result.id;
				           		 	          }
				           		 	        },
				           		 	        cStatus: 1,
				           		 	        resourcesCode: resourcesCode,
				           		 	        resourcesName: "resName_pin_list"
				           		 	    });
				           		 	    selectWindow.show();
		                    		}
		                    	}	
		                    },
			                { xtype: "textfield", name:"customerName", fieldLabel: "客户名称"}
			                
		            ]
		        },{
		        	xtype: "container",
	                layout: "hbox",
	                items: [
	                    { xtype: "textfield", name: "depositCode", fieldLabel: "认筹号" },
	                    { xtype: "datefield", name: "didTimeBefore",fieldLabel: "认筹日期",format:'Y-m-d'},
	                    {margin: "0 5 0 5",xtype: 'displayfield',value:'-'},
		                { xtype: "datefield", name: "didTimeAfter", format:'Y-m-d'}
//	                    { xtype: "datefield", name: "startTimeBefore", fieldLabel: "认筹有效开始日期",format:'Y-m-d' },
//	                    { xtype: "datefield", name: "endTimeAfter", fieldLabel: "认筹失效结束日期",format:'Y-m-d' }
	                ]
	            }
//		        ,{
//		        	xtype: "container",
//	                layout: "hbox",
//	                items: [
//	                    
//	                ]
//	            }
		        ,{
		            xtype: "container",
		            layout: "hbox",
		            items: [
						{ xtype: "datefield", name: "checkDateBefore", fieldLabel: "审核日期",format:'Y-m-d'},
						{margin: "0 5 0 5",xtype: 'displayfield',value:'-'},
						{ xtype: "datefield", name: "checkDateAfter", format:'Y-m-d'},
						{ 
	        	            xtype:'combobox',  
	        	            id:'user',  
	        	            store: agentGroupStore,
	        	            displayField: "userName",           
	        	            valueField: "id",  
	        	            fieldLabel:'经纪人',  
	        				name:'agentId',
	        				queryMode : 'local'
	        			}
		            ]
		        },{
		        	xtype: "container",
		            layout: "hbox",
		            items: [
						{ xtype: "datefield", name: "createTimeBefore1", fieldLabel: "录入日期",format:'Y-m-d'},
						{margin: "0 5 0 5",xtype: 'displayfield',value:'-'},
						{ xtype: "datefield", name: "createTimeAfter1", format:'Y-m-d'}
		            ]
	            },{
		            xtype: "container",
		            layout: "hbox",
		            items: [
		                { 
	    	            	xtype: "checkboxgroup",
	    	            	id:"ckStatus",
	    	            	name:"m_auditStatus",
	    	            	fieldLabel: "审核状态",
	    	            	width: 450,
	    	            	items:[{
	        	            		boxLabel:'待提交',
	        	            		inputValue:'0'
	        	            	},{
	        	            		boxLabel:'审核中',
	        	            		inputValue:'1'
	        	            	},{
	        	            		boxLabel:'已通过',
	        	            		inputValue:'3'
	        	            	},{
	        	            		boxLabel:'已退回',
	        	            		inputValue:'2'
	        	            	}
	    	                 ]
	                    }
		            ]
	            },{
		            xtype: "container",
		            layout: "hbox",
		            items: [
		                { 
							xtype: "checkboxgroup",
			            	id:"busStatus",
			            	name :"m_businessStatus",
			            	fieldLabel: "业务状态",
			            	width: 570,
			            	items:[{
				            		boxLabel:'认筹',
				            		inputValue:'1'
				            	},{
				            		boxLabel:'认筹转签约',
				            		inputValue:'3'
				            	},{
				            		boxLabel:'认筹转认购',
				            		inputValue:'2'
				            	},{
				            		boxLabel:'已更名',
				            		inputValue:'4'
				            	},{
				            		boxLabel:'退认筹',
				            		inputValue:'5'
				            	}
			                 ]
		            	}
		            ]
	            }
		        ],
		    buttons: [
				  	        { xtype: "button", text: "查询", 
				  	        	handler:function(){
				  	        		//获取通过checkboxgroup定义的checkbox值
				  	        		//审核状态
				  	        		var ckStatusValue = Ext.getCmp('ckStatus').getChecked();
				  	        		var ckStatus="";
				  	        		Ext.Array.each(ckStatusValue, function(item){
				  	        			ckStatus += item.inputValue+',' ;
				  	        		});
				  	        		gridStoreGroup.getProxy().extraParams.m_auditStatus = ckStatus;
				  	        		//业务状态
				  	        		var busStatusValue = Ext.getCmp('busStatus').getChecked();
				  	        		var busStatus="";
				  	        		Ext.Array.each(busStatusValue, function(item){
				  	        			busStatus += item.inputValue+',' ;
				  	        		});
				  	        		gridStoreGroup.getProxy().extraParams.m_businessStatus = busStatus;
				  	        		gridStoreGroup.load();
				  	        		var pagingTool=Ext.getCmp("pagingToolc");
				  	        		pagingTool.moveFirst();//跳至第一页
				  	        	}  
				  	        },
				  	        { xtype: "button", text: "清空",handler:function(){
				  	        		form.getForm().reset();
				  	        	}
				  	        }
				  	    ]    
	});
	
	var statistics = Ext.create('Ext.form.FormPanel',{
		items:[{
            xtype: "fieldcontainer",
            layout: "hbox",
            items: [
            	{xtype: "fieldcontainer", layout: "column",
    				items:[
    				    {xtype: "displayfield", value: "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;共"},
	    				{xtype: "displayfield", name: "info_sumRoom", value:"0"},
	    				{xtype: "displayfield", value: "套,&nbsp;&nbsp;&nbsp; "}
    				]
				},
				{xtype: "fieldcontainer", layout: "column",
    				items:[
	    				{xtype: "displayfield", name: "info_calculateArea", value:"0"},
	    				{xtype: "displayfield", value: "㎡,&nbsp;&nbsp;&nbsp; "},
    				]
				},
				{xtype: "fieldcontainer", layout: "column",
    				items:[
	    				{xtype: "displayfield", name: "info_Amount", value:"0", renderer: Ext.util.Format.numberRenderer('0,000.00')},
	    				{xtype: "displayfield", value: "元"},
    				]
				}
            ]
		}]
	});
		
	gridStoreGroup = Ext.create('Ext.data.Store', {
        fields: ["id","createTime","customerName", "isPaydeposit", "combinedName","roomStatus","houseTypeName","discountTotalPrice","payDepositAmount","totalRealAmount","userName","businessStatus","auditStatus","roomId","calculateArea"],
        pageSize: 10,  //页容量5条数据
        //是否在服务端排序 （true的话，在客户端就不能排序）
        remoteSort: false,
        proxy: {
            type: 'ajax',
            url: jypath+'/customer/payDeposit/list',
            actionMethods: { read: 'POST' },
            reader: {   //这里的reader为数据存储组织的地方，下面的配置是为json格式的数据，例如：[{"total":50,"rows":[{"a":"3","b":"4"}]}]
                type: 'json', //返回数据类型为json格式
                root: 'rows',  //数据
                totalProperty: 'total' //数据总条数
            }
        },
        autoLoad: true  //即时加载数据
    });
	
	gridStoreGroup.on("beforeload",function(){
        Ext.apply(gridStoreGroup.proxy.extraParams,form.getForm().getValues());
        //debugger
		var projectId = Ext.getCmp("groupProjectStore").getValue();
		gridStoreGroup.proxy.extraParams.projectId = projectId;
		if(projectId == "-1"){
			gridStoreGroup.proxy.extraParams.projectId = "";
		}
    });
	
	Math.formatFloat = function(f, digit) { 
	    var m = Math.pow(100, digit); 
	    return parseFloat(f * m, 10) / m; 
	}
	gridStoreGroup.on("load",function(){
		var discountTotalPrice = 0;
		var calculateArea = 0;
		var rows = gridStoreGroup.getCount();
		for(var i = 0; i < rows; i++){
			var rowData = gridStoreGroup.getAt(i).data;
			calculateArea += rowData.calculateArea;
			discountTotalPrice += rowData.discountTotalPrice;
		}
		statistics.getForm().findField("info_sumRoom").setValue(rows);
		statistics.getForm().findField("info_calculateArea").setValue(Math.formatFloat(calculateArea, 1));
		statistics.getForm().findField("info_Amount").setValue(Math.formatFloat(discountTotalPrice, 1));
    });
	
	var grid = Ext.create('Ext.grid.Panel', {
		minHeight:600,
        store: gridStoreGroup,
        columnLines: true,
        columns: [{  
            text : "查看",  
            dataIndex: 'actioncolumn',
            renderer: function(value,cellmeta,record,rowIndex,columnIndex,store) {
                var rec = grid.getStore().getAt(rowIndex);
//                if(rec.get('auditStatus')==0){
//                	return html = "<a href='"+jypath+"/customer/payDeposit/toView?id="+rec.get('id')+"&returnUrl=,marketing,pin,index' style='cursor:pointer'>查看</a>&nbsp;&nbsp;<a href='javascript:del("+rec.get('id')+")'>删除</a>"
//                	+"";
//                }
                //查看
                return html = "<a href='"+jypath+"/customer/payDeposit/toView?id="+rec.get('id')+"&returnUrl=,marketing,pin,index' style='cursor:pointer'>查看</a>";
            }
        },{
            text: '认筹日期',
            dataIndex: 'createTime',
            renderer:function(value){
            	return Ext.Date.format(new Date(value),'Y-m-d')
            }
        },{
            text     : '客户名称', 
            dataIndex: 'customerName'
        },{
            text     : '是否无房认筹',
            dataIndex: 'isPaydeposit',
            renderer:function(val){
            	if (val == 0) {
                    return '否';
                } else if (val == 1) {
                    return '是';
                }
                return val;
            }
        },{
            text     : '房号',
            dataIndex: 'combinedName',
            width:250,
            renderer: function(value,cellmeta,record,rowIndex,columnIndex,store) {
            	 var rec = grid.getStore().getAt(rowIndex);
            	 var roomId = rec.get('roomId');
            	 if(roomId!=null){
            		 return "<a style='text-decoration:none;' href='javascript:openWindow("+roomId+")'>"+value+"</a>";
            	 }
            	 return value;
            }
        },{
            text     : '房间状态',
            dataIndex: 'roomStatus',
            renderer : function(val) {
                if (val == 1) {
                    return '可售';
                } else if (val == 2) {
                    return '保留';
                }else if (val == 3) {
                    return '认筹';
                }else if (val == 4) {
                    return '认购';
                }else if (val == 5) {
                    return '签约';
                }else if (val == 6) {
                    return '销控';
                }else if (val == 7) {
                    return '暂不可售';
                }
                return val;
            }
        },{
            text     : '户型',
            dataIndex: 'houseTypeName',
            renderer : function(val) {
                if (val == 0) {
                    return '正常';
                } else if (val == 1) {
                    return '已关闭';
                }
                return val;
            }
        },{
            text     : '房屋总价(元)',
            dataIndex: 'discountTotalPrice', renderer: Ext.util.Format.numberRenderer('0,000.00')
        },{
            text     : '认筹金(元)',
            dataIndex: 'payDepositAmount', renderer: Ext.util.Format.numberRenderer('0,000.00')
        },{
            text     : '已收认筹金(元)',
            dataIndex: 'totalRealAmount',
            renderer:function(value){
            	if(value==null||value==""){
            		return "0.00";
            	}
            	return Ext.util.Format.number(value,'0,000.00');
            }
        },{
            text     : '经纪人',
            dataIndex: 'userName'
        },{
            text     : '业务状态',
            dataIndex: 'businessStatus',
            renderer : function(val) {
                if (val == 1) {
                    return '认筹';
                } else if (val == 2) {
                    return '认筹转认购';
                }else if (val == 3) {
                    return '认筹转签约';
                }else if (val == 4) {
                    return '已更名';
                }else if (val == 5) {
                    return '退认筹';
                }
                return val;
            }
        },{
            text     : '审核状态',
            dataIndex: 'auditStatus',
            renderer : function(val) {
                if (val == 0) {
                    return '待提交';
                } else if (val == 1) {
                    return '审核中';
                }else if (val == 2) {
                    return '已退回';
                }else if (val == 3) {
                    return '已通过';
                }
                return val;
            }
        },{  
            text : "操作",
            width:120,
            dataIndex: 'actioncolumn',
            renderer: function(value,cellmeta,record,rowIndex,columnIndex,store) {
                var rec = grid.getStore().getAt(rowIndex);
                var html = "";
                html = "<a href='"+jypath+"/customer/payDeposit/toView?id="+rec.get('id')+"&returnUrl=,marketing,pin,index' style='cursor:pointer'>查看</a>";
                if(rec.get('auditStatus')==0 || rec.get('auditStatus')==2){
                	//房间为认筹状态，可编辑
                	if(rec.get("roomStatus") == 3 || rec.get("roomStatus") == 1){
                		html += "&emsp;<a href='"+jypath+"/customer/payDeposit/toEdit?id="+rec.get('id')+"&returnUrl=,marketing,pin,index' style='cursor:pointer'>编辑</a>";
                	}
                	//审核状态为待提交时，可编辑
                	if(rec.get('auditStatus')==0){
                		html += "&emsp;<a href='javascript:delGroup("+rec.get('id')+")'>删除</a>";
                	}
                	return html;
                }
                //查看
                return html;
            }
        }],
        title: '认筹列表',
        dockedItems: [{  
            xtype: 'pagingtoolbar',  
            store: gridStoreGroup,   // GridPanel中使用的数据  
            dock: 'bottom',  
            displayInfo: true,  
            emptyMsg:"没有数据",  
            displayMsg:"显示从{0}条数据到{1}条数据，共{2}条数据",
            id:'pagingToolc'
        }
        ]
    });
	
		
		var defaultConfig = {
				defaults: {  
		            split: true,    //有分割线  
		            collapsible: true  //可以折叠
		        },
				items:[form,statistics,grid]
		};
		Ext.apply(this,defaultConfig);
		this.callParent(arguments);
		
	}
});



function delGroup(id){
    Ext.MessageBox.confirm("提示","是否删除该认筹记录?",function(btn,txt){
    	if(btn=="yes"){
    		Ext.Ajax.request({
    			 url: jypath+'/customer/payDeposit/delete',
                 params: { id: id},
                 method: 'POST',
                 callback: function (options, success, response) {
                	 if (success) {
                		 var obj = eval('(' + response.responseText + ')');
                		 if(obj.res == '100'){
                			 Ext.MessageBox.alert("系统提示","该账号没有删除权限");
                		 }else{
                			 Ext.MessageBox.alert("系统提示","删除认筹记录成功");
                			 gridStoreGroup.load();
                		 }
                	 }else{
                		 Ext.MessageBox.alert("系统提示","删除认筹记录失败！");
                	 }
                 }
    		});
        }
    });
}
